package com.xxgc.demo.controller;

import com.xxgc.demo.controller.pojo.ImageRecyclingPOJO;
import com.xxgc.demo.controller.result.Result;
import com.xxgc.demo.controller.vo.AddNewsVO;
import com.xxgc.demo.entity.News;
import com.xxgc.demo.service.INewsService;
import com.xxgc.demo.utils.RedisUtil;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * @Author: Sjy
 * @Date :2023/10/9 - 10 - 09 - 11:12
 * 新闻接口
 */
@Slf4j
@Tag(name = "新闻")
@RestController
@RequestMapping("/news")
public class NewsController {

    @Autowired
    private RedisUtil redisUtil;

    @Autowired
    private INewsService iNewsService;

    @Operation(summary = "添加新闻",description = "新闻")
    @PostMapping("/addNews")
    public Result addNews(@RequestBody AddNewsVO addNewsVO) {
        //-------------------------删除redis的记录--------------
        // /images/bg/20231011/406e43531fc743a09ae632d19ac34345.jpg
        String coverImage = addNewsVO.getCoverImage();
        String substring = coverImage.substring(coverImage.lastIndexOf("/") + 1, coverImage.lastIndexOf("."));
        //还原key
        String key = "recycling:image:"+substring;
        ImageRecyclingPOJO irPO = (ImageRecyclingPOJO) redisUtil.get(key);
        //----------redis也移除-----------
        redisUtil.lRemove("recycling_image",1,irPO);
        redisUtil.del(key);
        //---------------------------删除redis记录结束-----------
        News news = new News();
        BeanUtils.copyProperties(addNewsVO,news);
        iNewsService.save(news);

        return Result.ok().msg("新闻添加成功");
    }
}
